package com.vcredit.creditcat.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vcredit.creditcat.model.User;
import com.vcredit.creditcat.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vcredit.creditcat.framework.util.ImageUtil;
import com.vcredit.creditcat.model.Resource;
import com.vcredit.creditcat.security.SecurityHelper;
import com.vcredit.creditcat.service.UserService;

@Controller
public class MainController {
	@Autowired
	private UserService userService;
	@Autowired
	private ResourceService resourceService;

	@RequestMapping("/index")
	public String index() {
		return "login";
	}

	@RequestMapping("/main")
	public String main(ModelMap map) {
		map.put("user", userService.findById(SecurityHelper.getUserId()));
		map.put("baseMenus", userService.findMenu(SecurityHelper.getUserId()));
		return "index";
	}
	@ResponseBody
	@RequestMapping("/privileges")
	public Map<String,Object> privileges() {
		//查询按钮权限
		List<String> privileges=resourceService.findPrivilegesByUserId(SecurityHelper.getUserId(),1);
		//渠道数据查询权限
		List<Resource> channelData=resourceService.findByUserId(SecurityHelper.getUserId(),2);
		Map<String,Object> map=new HashMap();
		map.put("privileges",privileges.toString().replace("[","").replace("]","").replaceAll(" ",""));
		map.put("channelData",channelData);
		return map;
	}

	@ResponseBody
	@RequestMapping("/menu")
	public List<Resource> menu() {
		List<Resource> menus=userService.findMenu(SecurityHelper.getUserId());
		return menus;
	}

	@RequestMapping("/validateImage")
	public String validateImage(HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		Map<String, BufferedImage> m = ImageUtil.dynaImage();
		Iterator<String> it = m.keySet().iterator();
		if (it.hasNext()) {
			String dynaCode = it.next();
			request.getSession().setAttribute("imageVal", dynaCode);
			BufferedImage image = m.get(dynaCode);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(image, "jpeg", bos);

			byte[] bbs = bos.toByteArray();
			ServletOutputStream ouputStream = response.getOutputStream();
			ouputStream.write(bbs, 0, bbs.length);
			ouputStream.flush();
			ouputStream.close();
		}
		return null;
	}

}
